package com.example.test06thread.util;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 传递token参数
 */
public class ThreadLocalUtil {
    /**
     * 允许父子线程数据传递
     */
    private static final ThreadLocal<Map<String,Object>> transmit = new TransmittableThreadLocal<>();
    /**
     * 不允许父子线程传递
     */
    private static final ThreadLocal<Map<String,Object>> unTransmit = new ThreadLocal<>();

    public static void remove(){
        transmit.remove();
    }

    public static Object get(String key){
        return getContext(true).get(key);
    }

    public static void set(String key,Object value){
        getContext(true).put(key,value);
    }

    private static Map<String,Object> getContext(boolean isTrue){
        Map<String,Object> map = null;
        if(isTrue){
            map = transmit.get();
            if(map==null){
                map = new HashMap<>();
                transmit.set(map);
            }
        }else {
            map = unTransmit.get();
            if(map==null){
                map = new HashMap<>();
                unTransmit.set(map);
            }
        }
        return map;
    }

    public static Object get(String key,boolean isTrue){
        return getContext(isTrue).get(key);
    }

    public static void set(String key,Object value,boolean isTrue){
        getContext(isTrue).put(key,value);
    }

    public static void remove(boolean isTrue){
        if(isTrue){
            transmit.remove();
        }else {
            unTransmit.remove();
        }
    }
    private ThreadLocalUtil() {
    }
}
